package  
{
	import flash.display.DisplayObject;
	import flash.display.LoaderInfo;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	/**
	 * ...
	 * @author DarkGoodWIN
	 */
		 
	public class TNaperstokInfo extends TGameInfo
	{
		private var FriendsCont: TFriendsContainer = null;
		private var Ball: TBall = null;

		public var Glass1: TGlass = null;
		public var Glass2: TGlass = null;
		public var Glass3: TGlass = null;
		
		public var MoneyText: Ttext = null;
		public var UserNameText: Ttext = null;
		private var RankText: Ttext = null;
		private var TitulText: Ttext = null;
		
		public var Money: int = -1;
		private var CurrentMoney: int = -1;
				
		private var WinsOnline: int = 0;
		private var WinsOffLine: int = 0;
		private var LosesOnline: int = 0;
		private var LosesOffline: int = 0;
		
		private var timer: Timer = new Timer(1000);
		
		public var Log: TTextContainer = null;
		
		public var VKNaperstokAPI: NaperstokAPI;
		
		public var Prises: ByteArray;
		public var PrisesOnCase: ByteArray;
		
		private function RankLabel(Rank: int): String
		{
			if (Rank < -500)
			  return "Неудачник"
			else if (Rank < -100)
			  return "Рассеяный"
			else if (Rank < -10)
			  return "Невнимательный"
			else if (Rank < 10)
			  return "Новичок"
			else if (Rank < 50)
			  return "Любитель"
			else if (Rank < 100)
			  return "Мелкий шулер"
			else if (Rank < 500)
			  return "Матерый шулер"
			else if (Rank < 1000)
			  return "Профи"
			else if (Rank < 5000)
			  return "Дока"
			else
			  return "Гуру";
		}
		
		private var MaxAvailBotPlays: int = 10;
		private var WaitingBotTime: int = 0;
		
		public function IsInHome(): Boolean
		{
			return (VKNaperstokAPI.CurrentID == VKNaperstokAPI.ViewerID);
		}
		
		private function get AvailBotPlays(): int
		{
			return MaxAvailBotPlays - WaitingBotTime / TimeForBotPlayRestore;
		}
		
		private function GetBotStatusText(): String
		{
			if (AvailBotPlays < 1)
				return "Устал"
			else if (AvailBotPlays < (MaxAvailBotPlays / 2))
				return "Утомился"
			else
				return "Готов поиграть";
		}
		
		private function UpdateRank(): void
		{
			if (VKNaperstokAPI.CurrentID != BotID)
			{
				RankText.Visible = true;
				var Rank: int = WinsOnline * 5 + WinsOffLine * 3 - LosesOnline * 3 - LosesOffline * 1;
				RankText.Text = 'Рейтинг: ' + Rank.toString();
				TitulText.Text = RankLabel(Rank);
			}
			else
			{
				RankText.Visible = false;
				TitulText.Text = GetBotStatusText();
			}
		}
		
        public function OnSelfMoneyChange(O: Object): void
		{
			Money = O.Money;
			WaitingBotTime = O.WaitingBotTime;
			CurrentMoney = O.CurrentMoney;
			WinsOnline = O.Wins[0].value;
			LosesOnline = O.Wins[1].value;
			if (IsInHome())
			  UpdateRank();
			UpdateMoneyText();
		}
						
		private function OnDailyBonus(O: Object): void
		{
			Money = O.Money;
			UpdateMoneyText();
			var FriendsBonus: int = FriendsCont.Ctrls.length * 2;
			Log.Log("Ваш ежесуточный бонус:");
			Log.Log(O.MainBonus + " бублей, а также " + FriendsBonus + " бубля(ей) за друзей (по два за друга)");
			Log.Log("Заходите каждые сутки, чтобы увеличить бонус");
			Log.Log("");
			var Bonus: int = int(FriendsBonus) + int(O.MainBonus);
			new TModalMessage("Ваш бонус " + Bonus + " бублей", true, "Урааа!!!");
		}
		
		private function DailyBonus(IncBonus: Boolean): void
		{
			var DeltaVal1: int = FriendsCont.Ctrls.length * 2;
			VKNaperstokAPI.APIExecute(VKNaperstokAPI.DailyBonusCode(DeltaVal1, IncBonus), OnDailyBonus);
		}
		
		private var TimeForBotPlayRestore: int = 60 * 60;
				
		public function FillPrises(PrisesStr: String, PrisesOnCaseStr: String): void
		{
			StringUtils.String2ByteArr(PrisesStr, Prises, 255);
			StringUtils.String2ByteArr(PrisesOnCaseStr, PrisesOnCase, 255);
		}
		
		public function UpdatePrisesOnCase2Server(): void
		{
			VKNaperstokAPI.UpdatePrisesOnCase(StringUtils.ByteArr2String(PrisesOnCase));
		}
				
		public function onGetMessages(O: Object): void
		{
			Log.Log("<b>Пока вы были в оффлайн</b>");
			var W: String = O.OfflineCount[0].value;
			var L: String = O.OfflineCount[1].value;
			if ((W == "")||(W == null))
			  W = "0";
			if ((L == "")||(L == null))
			  L = "0";
    	    Log.Log("Вас победили: " + L + " раз(а)");
			Log.Log("Вам проиграли: " + W + " раз(а)");
			Log.Log("");
			
			FillPrises(O.Prises, O.PrisesOnCase);
			
			if (O.AfterBonusTime > 60 * 60 * 24)
			{
				if (O.AfterBonusTime < 2 * 60 * 60 * 24)
					DailyBonus(true)
				else
					DailyBonus(false);
			}
			WinsOffLine = O.OfflineWins[0].value;
			LosesOffline = O.OfflineWins[1].value;
			WaitingBotTime = O.WaitingBotTime;
			UpdateRank();
		}
		
		public function GetMessages(): void
		{
			VKNaperstokAPI.APIExecute(VKNaperstokAPI.GetMessagesCode(), onGetMessages);
		}
		
		public function Win(): void
		{
			UpdateMoneyToServ(true);			
			Log.Log("Вы выиграли у " + Ball.FriendName + " " + Ball.Price.toString() + " бублей");
		}
		
		public function Lose(): void
		{
			UpdateMoneyToServ(false);			
			Log.Log("Вы проиграли у " + Ball.FriendName + " " + Ball.Price.toString() + " бублей");
		}
				
		public function GoHome(): void
		{
			GoToID(VKNaperstokAPI.ViewerID, "Вы");
		}
				
		private function PlaceBotBall(): void
		{
			if (fNextID != BotID)
				return;
			if (AvailBotPlays < 1)
			{
				Log.Log("Хомяк устал, зайдите позже");
				Ball.State = TBall.StateOnDesk;
				return;
			}
   			var G: Number = Math.random();
			
    		if (G <= 1 / 3)
		        Glass1.DoPlaceBall()
			else if (G <= 2 / 3)
			    Glass2.DoPlaceBall()
			else if (G <= 3 / 3)
			    Glass3.DoPlaceBall();
		}
		
		private function OnGetUserInfo(O: Object): void
		{
			UserNameText.Text = fNextUserName;
			VKNaperstokAPI.CurrentID = fNextID;
			Ball.IsFriendBall = (!IsInHome());
			Glass1.ToDown();
			Glass2.ToDown();
			Glass3.ToDown();
			
			if (O.Info[0]['value'] == "")
			  CurrentMoney = 50
			else
			  CurrentMoney = O.Info[0]['value'];
			  
			if (IsInHome())
			  Money = CurrentMoney;
			  
			 UpdateMoneyText();
			  
			if (O.Info[1]['value'] == 1)
			  Glass1.DoPlaceBall()
			else if (O.Info[1]['value'] == 2)
			  Glass2.DoPlaceBall()
			else if (O.Info[1]['value'] == 3)
			  Glass3.DoPlaceBall()
    		else
			  Ball.State = TBall.StateOnDesk
			
			Ball.SetTextInfo();
			WinsOnline = O.Wins[0].value;
			LosesOnline = O.Wins[1].value;
			WinsOffLine = O.Wins[2].value;
			LosesOffline = O.Wins[3].value;
			UpdateRank();
			PlaceBotBall();	
			FillPrises(O.Prises, O.PrisesOnCase);
		}
			
		private var fNextUserName: String = "";
		private var fNextID: int = -1;
		public override function GoToID(ID: int, UserName: String): void
		{
			Glass1.Ctrl.alpha = 100; 
			Glass2.Ctrl.alpha = 100; 
			Glass3.Ctrl.alpha = 100; 			
			GetUserInfo(ID, UserName);
		}
		
		public function UpdateMoneyText(): void
		{
			MoneyText.Text = "Бубли: " + Money.toString();
		}
		
		public function BallMoved(e: MouseEvent): void
		{
			Glass1.CheckBall(e.stageX, e.stageY);
			Glass2.CheckBall(e.stageX, e.stageY);
			Glass3.CheckBall(e.stageX, e.stageY);
		}
		
		public function BallPlaced(e: MouseEvent): Boolean
		{
			var B: Boolean = false;
			if (Glass1.PlaceBall(e.stageX, e.stageY))
			  B = true
			else if (Glass2.PlaceBall(e.stageX, e.stageY))
			  B = true
			else if (Glass3.PlaceBall(e.stageX, e.stageY))
			  B = true;
			return B;
		}
		
		/* 
		private function doAddAd(O: Object): void
		{
			Log.Log("ad");
			Log.Log(O.title);
		}
		
		private function onGetAds(O: Object): void
		{
			Log.Log(O.list);
			for each (var Ad:* in O)
			{
			  if (Ad != null)
			    doAddAd(Ad);
			}
		}
		*/

		private function GetUserInfo(ID: int, UserName: String): void
		{
			fNextUserName = UserName;
			fNextID = ID;
			VKNaperstokAPI.APIExecute(VKNaperstokAPI.GetUserInfoCode(ID, WaitingBotTime < 0), OnGetUserInfo);
		    //api("getAds", {"count":1, "type":3 }, onGetAds);
		}
		
		public function UpdateBallPosToServ(NewPos: int, onComplite: Function): void
		{
			VKNaperstokAPI.APIPutVariable(1505, NewPos.toString(), VKNaperstokAPI.CurrentID, onComplite);
		}
		
		public function UpdateMoneyToServ(Win: Boolean): void
		{
			var Price: int = 0;
			if (Win)
				Price = Ball.Price
			else
				Price = - Ball.Price;
			VKNaperstokAPI.APIExecute(VKNaperstokAPI.UpdateMoneyToServCode(Win, TimeForBotPlayRestore, Price), OnSelfMoneyChange);
		}
		
		private function OnHomeClick(e: MouseEvent): void
		{
			GoHome();
		}
		
		private function OnInfoClick(e: MouseEvent): void
		{
			new TInfoDialog();
		}
		
		private function OnShopBtnClick(e: MouseEvent): void
		{
			new TNaperstokShop(this);
		}
		
		private function OnRichBtnClick(e: MouseEvent): void
		{
			new TNaperstokRich(this);			
		}
		
		private var BotID: int = 94893197;
		
		private function GoToBot(e: MouseEvent): void
		{
			GoToID(BotID, "Хомяк");
		}
		
		public function GreateControls(MainControl: TControl): void
		{
			UserNameText = new Ttext("", MainControl, 15, 10, false);
			UserNameText.Height = 200;
			UserNameText.Width = 500;
			
			RankText  = new Ttext("", MainControl, 15, 90, false);
			RankText.Height = 200;
			RankText.Width = 500;
			
			TitulText = new Ttext("", MainControl, 15, 40, false);
			TitulText.Height = 250;
			TitulText.Width = 500;
			
			MoneyText = new Ttext("", MainControl, 350, 45, false);
			MoneyText.Height = 200;
			MoneyText.Width = 1000;
			UpdateMoneyText();

			var TextInfo: Ttext = new Ttext("", MainControl, 0, 180, false);
			TextInfo.Height = 200;
			TextInfo.Width = 1000;			
			
			var Desk: TPictureControl = new TPictureControl(res.desk, MainControl, -250, 320);
			Desk.Height = 275;
			Desk.Width = 1100;
			
			Ball = new TBall(MainControl, 435, 175, this, TextInfo);
						
			Log = new TTextContainer(MainControl, 0xFFFFBB, 560, 0, 240, 500, false, true, true);
			
			var gy: int = 300;
			Glass1 = new TGlass(MainControl, 80, gy, Ball, Log, 1);
			Glass2 = new TGlass(MainControl, 240, gy, Ball, Log, 2);
			Glass3 = new TGlass(MainControl, 400, gy, Ball, Log, 3);
			
			var InfoButton: InvControl = new InvControl(res.info, MainControl, 500, 15);
			InfoButton.addEventListener(MouseEvent.CLICK, OnInfoClick); 
			
			var ShopBtn: InvControl = new InvControl(res.ShopBtn, MainControl, 420, 15);
			ShopBtn.addEventListener(MouseEvent.CLICK, OnShopBtnClick); 
			
			var RichBtn: InvControl = new InvControl(res.rich_btn, MainControl, 340, 15);
			RichBtn.addEventListener(MouseEvent.CLICK, OnRichBtnClick);
			
			var HomeBtn: InvControl = new InvControl(res.home, MainControl, 15, 530);
			HomeBtn.Hint = "К себе";
			HomeBtn.addEventListener(MouseEvent.CLICK, OnHomeClick);
			
			var Bot: InvControl = new InvControl(res.bot, MainControl);
			Bot.Hint = "Хомяк";
			Bot.addEventListener(MouseEvent.CLICK, GoToBot);
			FriendsCont = new TFriendsContainer(MainControl, 70, 510, 730, 80, this);
			FriendsCont.AddControl(Bot);
							
			//InitGame();
		}
		
		public override function InitGame(): void
		{
		    GoHome();
			GetMessages();			
		}
		
		private function OnUpdateWaitingBotTime(O: Object): void
		{
			WaitingBotTime = O.BotWaitTime;
			if (WaitingBotTime < 0)
				WaitingBotTime = 0;
		}
		
		private function UpdateWaitingBotTime(IncCount: int): void
		{
			if (WaitingBotTime >= 0)
				VKNaperstokAPI.APIExecute(VKNaperstokAPI.UpdateBotWaitTimeCode(IncCount), OnUpdateWaitingBotTime)
			else
				VKNaperstokAPI.ClearBotWaitTimeCode();
		}
		
		private var TimeForUpdateBotPlay: int = 0;
		
		private function OnTimer(e: TimerEvent): void
		{
			WaitingBotTime = WaitingBotTime - 1;
			TimeForUpdateBotPlay = TimeForUpdateBotPlay + 1;
			if (TimeForUpdateBotPlay >= 30)
			{
				TimeForUpdateBotPlay = 0;
				UpdateWaitingBotTime(-30);				
			}
			if (WaitingBotTime < 0)
				WaitingBotTime = 0;
		}
		
		private function LoadingFrame(e: Event): void
		{
			if (Loading.Ctrl.numChildren < 1)
			  return;
			Loading.Ctrl.getChildAt(0).x += 10;
			if (Loading.Ctrl.getChildAt(0).x > 350)
			  Loading.Ctrl.getChildAt(0).x = 250;
		}
		
		protected override function StartLoading(): void
		{
			Loading = new TModalWindow(0.1);
			var C: TControl = new TPictureControl(res.load, Loading, 250, 230);
			Loading.AddChild(C);
			C.addEventListener(Event.ENTER_FRAME, LoadingFrame);
			
		}
		
		protected override function EndLoading(): void
		{
			Loading.Ctrl.removeChildAt(0);
			Loading.Close();			
		}
		
		public function TNaperstokInfo(flashvars: Object) 
		{
			VKNaperstokAPI = new NaperstokAPI(flashvars, this);
			Prises = new ByteArray();
			PrisesOnCase = new ByteArray();
			super(VKNaperstokAPI);
			timer.addEventListener(TimerEvent.TIMER, OnTimer);
			timer.start();
			VKNaperstokAPI.ViewerID = flashvars['viewer_id'];
			VKNaperstokAPI.CurrentID = VKNaperstokAPI.ViewerID;
		}
		
	}
}